import utime as time
import usocket
import _thread  
import yun_network
from modem import net
from driver import TIMER


def doConnect3(host,port):
    global sock,send_state,sock
    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    try :         
        sock.connect((host,port))   #尝试tcp连接，失败会报错
        send_state=True     #tcp连接标志位
    except :
        send_state=False
    print('send_state',send_state)
    _thread.start_new_thread(tcprecv3,()) #开启接收数据线程


#接收数据线程
def tcprecv3():
    global sock,send_state
    print('Running thread tcprecv...')
    while True:
        time.sleep_ms(50)
        if send_state:
            try:
                recvdata=b''
                recvdata=sock.recv(255)     #接收tcp服务器信息
            except OSError:
                print('TCP3 OSError')
            if len(recvdata)!=0:
                print(recvdata)
        else:
            print("close thread -----------------")
            _thread.exit()  #结束线程


def demo(host,port):   
    global g_host ,g_port,send_state
    global sock
    g_host=host
    g_port=port
    print(host,port)   
    doConnect3(host,port)


#上传数据，根据上传是否成功判断TCP连接情况
send_state=False
def update3(value):
    global g_host,g_port,sock
    global sock,send_state
    try:
        msg=str(value) + "\r\n"
        print(msg)
        sock.send(msg)  #tcp断开后上传数据会报错
    except:
        print("\r\nsocket3 error,do reconnect ")
        send_state=False
        sock.close()    #关闭tcp
        time.sleep(1)
        doConnect3(g_host,g_port)   #重连tcp平台


#开启计时器定时上传信息
count_offline=0
def timer_cb(args):
    global  count_offline,send_state
    count_offline += 1  #计时
    if send_state:
        update3("11111")    #1秒一次上传
        count_offline=0
    if send_state==False:     
        if count_offline>=5:    #5秒一次上传，时间按需更改
            count_offline= 0
            update3("11111")



if __name__ == '__main__':
    a = '112.125.89.8'  #host
    b = 45186   #port
    c = 1000    #定时器时间ms
    yun_network.connect_network()   #联网
    demo(a,b)   #tcp连接

    #联网后开启定时器，开始上传数据
    tim0 = TIMER(0)
    tim0.open(period=c, mode=TIMER.PERIODIC, callback=timer_cb)      

    while True:
        time.sleep(1)
        print("csq：",net.getCsq()) #信号强度
        





